{% extends "base.html" %}

{% block title %}XCQuant 量化交易管理平台{% endblock %}

{% block content %}
<div class="row">
    <!-- 欢迎信息 -->
    <div class="col-12">
        <div class="jumbotron bg-primary text-white rounded p-4 mb-4">
            <h1 class="display-4">
                <i class="fas fa-chart-line me-3"></i>欢迎使用 XCQuant
            </h1>
            <p class="lead">专业的量化交易管理平台，提供策略开发、回测、实盘交易和监控功能</p>
            <hr class="my-4">
            <p>开始您的量化交易之旅，探索数据驱动的投资策略</p>
            <a class="btn btn-light btn-lg" href="{{ url_for('dashboard') }}" role="button">
                <i class="fas fa-tachometer-alt me-2"></i>进入监控面板
            </a>
        </div>
    </div>
</div>

<div class="row">
    <!-- 系统概览 -->
    <div class="col-lg-3 col-md-6 mb-4">
        <div class="card border-left-primary shadow h-100 py-2">
            <div class="card-body">
                <div class="row no-gutters align-items-center">
                    <div class="col mr-2">
                        <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">
                            系统状态
                        </div>
                        <div class="h5 mb-0 font-weight-bold text-gray-800" id="system-status-text">
                            正在加载...
                        </div>
                    </div>
                    <div class="col-auto">
                        <i class="fas fa-server fa-2x text-gray-300"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 活跃策略 -->
    <div class="col-lg-3 col-md-6 mb-4">
        <div class="card border-left-success shadow h-100 py-2">
            <div class="card-body">
                <div class="row no-gutters align-items-center">
                    <div class="col mr-2">
                        <div class="text-xs font-weight-bold text-success text-uppercase mb-1">
                            活跃策略
                        </div>
                        <div class="h5 mb-0 font-weight-bold text-gray-800" id="active-strategies">
                            正在加载...
                        </div>
                    </div>
                    <div class="col-auto">
                        <i class="fas fa-robot fa-2x text-gray-300"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 总收益 -->
    <div class="col-lg-3 col-md-6 mb-4">
        <div class="card border-left-info shadow h-100 py-2">
            <div class="card-body">
                <div class="row no-gutters align-items-center">
                    <div class="col mr-2">
                        <div class="text-xs font-weight-bold text-info text-uppercase mb-1">
                            总收益
                        </div>
                        <div class="h5 mb-0 font-weight-bold text-gray-800" id="total-profit">
                            正在加载...
                        </div>
                    </div>
                    <div class="col-auto">
                        <i class="fas fa-dollar-sign fa-2x text-gray-300"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 活跃告警 -->
    <div class="col-lg-3 col-md-6 mb-4">
        <div class="card border-left-warning shadow h-100 py-2">
            <div class="card-body">
                <div class="row no-gutters align-items-center">
                    <div class="col mr-2">
                        <div class="text-xs font-weight-bold text-warning text-uppercase mb-1">
                            活跃告警
                        </div>
                        <div class="h5 mb-0 font-weight-bold text-gray-800" id="active-alerts">
                            正在加载...
                        </div>
                    </div>
                    <div class="col-auto">
                        <i class="fas fa-exclamation-triangle fa-2x text-gray-300"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="row">
    <!-- 快速操作 -->
    <div class="col-lg-6 mb-4">
        <div class="card shadow">
            <div class="card-header py-3">
                <h6 class="m-0 font-weight-bold text-primary">
                    <i class="fas fa-bolt me-2"></i>快速操作
                </h6>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-6 mb-3">
                        <a href="{{ url_for('dashboard') }}" class="btn btn-primary btn-block">
                            <i class="fas fa-tachometer-alt me-2"></i>监控面板
                        </a>
                    </div>
                    <div class="col-md-6 mb-3">
                        <a href="{{ url_for('strategies') }}" class="btn btn-success btn-block">
                            <i class="fas fa-robot me-2"></i>策略管理
                        </a>
                    </div>
                    <div class="col-md-6 mb-3">
                        <a href="{{ url_for('alerts') }}" class="btn btn-warning btn-block">
                            <i class="fas fa-exclamation-triangle me-2"></i>告警管理
                        </a>
                    </div>
                    <div class="col-md-6 mb-3">
                        <a href="{{ url_for('reports') }}" class="btn btn-info btn-block">
                            <i class="fas fa-file-alt me-2"></i>报告查看
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 系统信息 -->
    <div class="col-lg-6 mb-4">
        <div class="card shadow">
            <div class="card-header py-3">
                <h6 class="m-0 font-weight-bold text-primary">
                    <i class="fas fa-info-circle me-2"></i>系统信息
                </h6>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-borderless">
                        <tbody>
                            <tr>
                                <td><strong>平台版本:</strong></td>
                                <td>XCQuant v1.0.0</td>
                            </tr>
                            <tr>
                                <td><strong>运行时间:</strong></td>
                                <td id="uptime">正在加载...</td>
                            </tr>
                            <tr>
                                <td><strong>CPU使用率:</strong></td>
                                <td id="cpu-usage">正在加载...</td>
                            </tr>
                            <tr>
                                <td><strong>内存使用率:</strong></td>
                                <td id="memory-usage">正在加载...</td>
                            </tr>
                            <tr>
                                <td><strong>最后更新:</strong></td>
                                <td id="last-update">正在加载...</td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 最近告警 -->
<div class="row">
    <div class="col-12">
        <div class="card shadow">
            <div class="card-header py-3 d-flex justify-content-between align-items-center">
                <h6 class="m-0 font-weight-bold text-primary">
                    <i class="fas fa-bell me-2"></i>最近告警
                </h6>
                <a href="{{ url_for('alerts') }}" class="btn btn-sm btn-outline-primary">
                    查看全部
                </a>
            </div>
            <div class="card-body">
                <div id="recent-alerts">
                    <div class="text-center">
                        <div class="spinner-border text-primary" role="status">
                            <span class="visually-hidden">加载中...</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_scripts %}
<script>
$(document).ready(function() {
    // 加载系统概览数据
    loadSystemOverview();
    
    // 加载最近告警
    loadRecentAlerts();
    
    // 定时刷新数据
    setInterval(function() {
        loadSystemOverview();
        loadRecentAlerts();
    }, 30000); // 30秒刷新一次
});

function loadSystemOverview() {
    $.get('/api/v1/dashboard/data')
        .done(function(response) {
            if (response.success) {
                const data = response.data;
                
                // 更新系统状态
                const systemStatus = data.system?.status || 'unknown';
                $('#system-status-text').text(getStatusText(systemStatus));
                
                // 更新活跃策略
                const activeStrategies = data.strategies?.summary?.active_strategies || 0;
                $('#active-strategies').text(activeStrategies + ' 个');
                
                // 更新总收益
                const totalProfit = data.strategies?.summary?.total_profit || 0;
                $('#total-profit').text(formatCurrency(totalProfit));
                
                // 更新活跃告警
                const activeAlerts = data.alerts?.stats?.active_count || 0;
                $('#active-alerts').text(activeAlerts + ' 个');
                
                // 更新系统信息
                if (data.system?.current) {
                    $('#cpu-usage').text(data.system.current.cpu_percent.toFixed(1) + '%');
                    $('#memory-usage').text(data.system.current.memory_percent.toFixed(1) + '%');
                }
                
                $('#last-update').text(new Date().toLocaleString());
            }
        })
        .fail(function() {
            console.error('加载系统概览数据失败');
        });
}

function loadRecentAlerts() {
    $.get('/api/v1/alerts?limit=5')
        .done(function(response) {
            if (response.success) {
                const alerts = response.data.alerts;
                const alertsHtml = renderRecentAlerts(alerts);
                $('#recent-alerts').html(alertsHtml);
            }
        })
        .fail(function() {
            $('#recent-alerts').html('<div class="text-muted">加载告警数据失败</div>');
        });
}

function renderRecentAlerts(alerts) {
    if (alerts.length === 0) {
        return '<div class="text-muted">暂无告警</div>';
    }
    
    let html = '<div class="list-group list-group-flush">';
    alerts.forEach(function(alert) {
        const levelClass = getLevelClass(alert.level);
        const levelIcon = getLevelIcon(alert.level);
        const timeAgo = getTimeAgo(alert.created_at);
        
        html += `
            <div class="list-group-item list-group-item-action">
                <div class="d-flex w-100 justify-content-between">
                    <h6 class="mb-1">
                        <i class="${levelIcon} ${levelClass} me-2"></i>
                        ${alert.title}
                    </h6>
                    <small class="text-muted">${timeAgo}</small>
                </div>
                <p class="mb-1">${alert.message}</p>
                <small class="text-muted">状态: ${getStatusText(alert.status)}</small>
            </div>
        `;
    });
    html += '</div>';
    
    return html;
}

function getStatusText(status) {
    const statusMap = {
        'healthy': '健康',
        'warning': '警告',
        'error': '错误',
        'critical': '严重',
        'active': '活跃',
        'resolved': '已解决',
        'unknown': '未知'
    };
    return statusMap[status] || status;
}

function getLevelClass(level) {
    const classMap = {
        'info': 'text-info',
        'warning': 'text-warning',
        'error': 'text-danger',
        'critical': 'text-danger'
    };
    return classMap[level] || 'text-secondary';
}

function getLevelIcon(level) {
    const iconMap = {
        'info': 'fas fa-info-circle',
        'warning': 'fas fa-exclamation-triangle',
        'error': 'fas fa-times-circle',
        'critical': 'fas fa-exclamation-circle'
    };
    return iconMap[level] || 'fas fa-circle';
}

function formatCurrency(amount) {
    return new Intl.NumberFormat('zh-CN', {
        style: 'currency',
        currency: 'CNY'
    }).format(amount);
}

function getTimeAgo(timestamp) {
    const now = new Date();
    const time = new Date(timestamp);
    const diff = now - time;
    
    const minutes = Math.floor(diff / 60000);
    const hours = Math.floor(diff / 3600000);
    const days = Math.floor(diff / 86400000);
    
    if (days > 0) return days + '天前';
    if (hours > 0) return hours + '小时前';
    if (minutes > 0) return minutes + '分钟前';
    return '刚刚';
}
</script>
{% endblock %}